package com.my.house.common.config;

import com.my.house.common.ApiAuth;
import com.my.house.common.Constants;
import com.my.house.common.utils.ThreadLocalHolder;
import com.my.house.domain.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import java.util.Objects;
import java.util.Optional;

/**
 * 用户权限检查拦截器
 * @author jitao
 */
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 缓存servletRequest进线程绑定变量备用
        boolean anonymous = false, admin = false;
        if (handler instanceof HandlerMethod method) {
            ApiAuth apiAuth = method.getMethodAnnotation(ApiAuth.class);
            if (Objects.isNull(apiAuth)) {
                apiAuth = method.getMethod().getDeclaringClass().getAnnotation(ApiAuth.class);
            }
            anonymous = Optional.ofNullable(apiAuth).map(ApiAuth::anonymous).orElse(false);
            admin = Optional.ofNullable(apiAuth).map(ApiAuth::admin).orElse(false);
        }
        HttpSession session = request.getSession();
        Object obj = session.getAttribute(Constants.USER);
        User user = null;
        if (obj != null) {
            user = (User) obj;
            ThreadLocalHolder.setUser(user);
        }
        String uri = request.getRequestURI();
        String method = request.getMethod();
        if (!anonymous && Objects.isNull(user)) {
            log.error("{}--{}--{},permission denied------> no_login", uri, method, session.getId());
            if (uri.startsWith("/api")) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            } else {
                response.setStatus(HttpServletResponse.SC_FOUND);
                response.sendRedirect("/page/login.html");
            }
            return false;
        }
        if (admin && (Objects.isNull(user) || !user.getAdmin())) {
            log.error("{}-{},permission denied------> not admin", uri, method);
            if (uri.startsWith("/api")) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            } else {
                response.setStatus(HttpServletResponse.SC_FOUND);
                response.sendRedirect("/page/login.html");
            }
            return false;
        }
        return true;
    }
}
